package com.csdj.t309.geamtest.controller;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@ServerEndpoint("/ws/test/{user}")
@Component
public class WebSocketController {

    /**
     * currentuser 记录现在的用户
     */
    private String currentUser;

    /**
     * 用集合保存相对应用户 session Id
     */
    private static Map<String ,String> userName = new HashMap<String,String>();

    private static Set<Session> login = new HashSet<>();

    //连接执行的方法
    @OnOpen
    public void onOpen(@PathParam("user") String user, Session session){
        currentUser = user;


        //存放所有的连接的用户
        userName.put(session.getId(),user);
        //
        login.add(session);

        System.out.println("用户:"+user+" 对应的Id:"+ session.getId());
        try {
            //向前台响应信息
            String nameAll ="";
            String link="";
            for (String s:userName.keySet()) {
                nameAll +=link+userName.get(s);
                link=",";
            }
            for (Session s:login) {
                s.getBasicRemote().sendText("userKet&"+nameAll);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //收到信息执行的方法
    @OnMessage
    public void onMessage(String message,Session session ){
        //通过键读取值
        for (Session s:login) {
            if(s.isOpen()){
                try {
                    //将所有用户的输入内容发送到前端
                    s.getBasicRemote().sendText("conter&"+currentUser+"说:"+message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //连接关闭时执行
    @OnClose
    public void  onClose(Session session, CloseReason closeReason){
        System.out.println(String.format("Session %s closed because of %s", session.getId(), closeReason));
    }
    //错误时执行
    @OnError
    public void onError(Throwable t){
        t.printStackTrace();
    }
}
